<template>
  <main-page>
    <div slot="body">
      <el-form :inline="true" :model="search" size="mini">
        <el-form-item>
          <el-input v-model="search.loginName" placeholder="登录账号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getMemberList">查询</el-button>
          <el-button type="primary" @click="dialogFormVisible = true;">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="id" width="80"></el-table-column>
        <el-table-column prop="loginName" label="登录账号"></el-table-column>
        <el-table-column prop="realName" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="tel" label="电话"></el-table-column>
        <el-table-column label="用户状态">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.userStatus == 0 ? '锁定' : '正常'" placement="top">
              <el-switch
                v-model="scope.row.userStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="updateStatus(scope.row)"
              ></el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="账户类型">
          <template slot-scope="scope">
            <template v-if="scope.row.userType == 1">系统管理员</template>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template slot-scope="scope">{{scope.row.createTime | datetime}}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              title="编辑"
              size="small"
              @click="handleClick2EditById(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              title="删除"
              size="small"
              @click="handleClick2DeleteById(scope.row.id)"
            ></el-button>
            <el-button
              type="primary"
              icon="el-icon-s-promotion"
              circle
              title="角色授权"
              size="small"
              @click="authThisMember(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination :listNum="listNum" @currentChange="handleCurrentChange"></pagination>

      <el-dialog title="用户管理" :visible.sync="dialogFormVisible" width="40%">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" autocomplete="off" placeholder="用户登录账号"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="form.realName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="form.tel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户类型" prop="userType">
            <el-select v-model="form.userType" style="width:100%">
              <el-option :key="1" label="系统管理员" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像" prop="cover">
              <!-- :action="rootApi + '/api/uploadFile'" -->
            <el-upload
              class="avatar-uploader"
              :action="rootApi"
              :on-remove="handleRemove"
              :on-success="handleAvatarSuccess"
              :before-upload="handleBeforeUpload"
              :limit="1"
            >
              <img v-if="form.cover" :src="form.cover" class="avatar">
              <i class="el-icon-plus avatar-uploader-icon" v-else></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </div>
      </el-dialog>

      <el-dialog title="用户授权" :visible.sync="dialogAuthFormVisible" width="40%">
        <el-form :model="authForm" label-width="80px">
          <el-form-item label="选择角色">
            <el-select v-model="authForm.roleIds" multiple placeholder="请选择" style="width: 100%">
              <el-option
                v-for="role in roleList"
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onAuthFormSubmit">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </main-page>
</template>

<script>
import MainPage from "common/Main";

import {
  getMemberList,
  saveMember,
  deleteMemberById,
  updateMemberById
} from "api/MemberApi";

import {
  getAllRolesList,
  saveRoleByMemberId,
  getRoleIdListByMemberId
} from "api/RolesApi";

import {deleteFileByUrl} from 'api/FileApi'

import { config } from "assets/js/Data";

export default {
  name: "MemberList",
  components: {
    MainPage
  },
  data() {
    var validateTel = (rule, value, callback) => {
      if (!/^1[34578]\d{9}$/.test(value)) {
        callback(new Error("请输入正确格式的手机号"));
      } else callback();
    };
    return {
      rootApi: process.env.VUE_APP_UPLOAD_URL,
      tableData: [],
      listNum: 1,
      search: {
        currentIndex: 1,
        loginName: ""
      },
      form: {
        id: "",
        email: "",
        realName: "",
        tel: "",
        userType: "",
        cover: ''
      },
      rules: {
        email: [
          { required: true, message: "请输入邮箱" },
          { type: "email", message: "输入正确格式的邮箱" }
        ],
        realName: [{ required: true, message: "请输入姓名" }],
        tel: [
          { required: true, message: "请输入手机号" },
          { validator: validateTel }
        ],
        userType: [{ required: true, message: "请选择用户类型" }]
      },
      dialogFormVisible: false,
      dialogAuthFormVisible: false,
      roleList: [],
      authForm: {
        userId: "",
        roleIds: []
      }
    };
  },
  methods: {
    getMemberList() {
      getMemberList(this.search).then(res => {
        if (res) {
          this.tableData = res.datas;
          this.listNum = res.pagination.totalCount;
        }
      });
    },
    handleCurrentChange(page) {
      this.search.currentIndex = page;
      this.getMemberList();
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            //修改
            updateMemberById(this.form).then(res => {
              if (res) {
                this.$base.showOk();
                this.dialogFormVisible = false;
                this.getMemberList();
              }
            });
          } else {
            //保存
            saveMember(this.form).then(res => {
              if (res) {
                this.$base.showOk();
                this.dialogFormVisible = false;
                this.getMemberList();
              }
            });
          }
        }
      });
    },
    handleClick2EditById(row) {
      this.dialogFormVisible = true;
      this.$base.set2Form(this.form, row);
    },
    handleClick2DeleteById(id) {
      this.$base.deleteConfirm(() => {
        deleteMemberById({ id }).then(res => {
          if (res) {
            this.$base.deleteOk();
            this.getMemberList();
          }
        });
      });
    },
    updateStatus(row) {
      updateMemberById({
        id: row.id,
        userStatus: row.userStatus
      }).then(res => {
        if (res) {
          this.$base.showOk();
          this.dialogFormVisible = false;
          this.getMemberList();
        }
      });
    },
    authThisMember(id) {
      this.dialogAuthFormVisible = true;
      this.authForm.userId = id;

      //获取所有的角色
      getAllRolesList().then(res => {
        if (res) {
          this.roleList = res;
        }
      });

      //通过memberId 查询授权的角色
      getRoleIdListByMemberId({ memberId: id }).then(res => {
        if (res) {
          this.authForm.roleIds = res;
        }
      });
    },
    onAuthFormSubmit() {
      saveRoleByMemberId(this.authForm).then(res => {
        if (res) {
          this.$base.showOk("角色授权成功");
        }
      });
    },
    handleRemove(file, fileList) {
      this.deleteFileByUrl()
    },
    handleBeforeUpload(file) {
      this.deleteFileByUrl()
    },
    deleteFileByUrl () {
      deleteFileByUrl({
        key: this.form.cover,
        module: config.module.UTILS
      }).then(res => {
        if (res) {
        }
      });
    },
    handleAvatarSuccess (res, file) {
      if(res.meta.success) {
        this.form.cover = res.data[0]
      }
    }
  },
  created() {
    this.getMemberList();
  },
  watch: {
    dialogFormVisible(newDialogFormVisible) {
      if (!newDialogFormVisible) {
        this.$base.clearObj(this.form);
      }
    },
    dialogAuthFormVisible(newDialogAuthFormVisible) {
      if (!newDialogAuthFormVisible) {
        this.$base.clearObj(this.authForm);
      }
    }
  }
};
</script>

<style lang="stylus" scoped></style>
